from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from rider.models import Rider
from rider.serializers import RiderSerializer
from station.serializers import StationSerializer
from trade.models import Orders, ExpressInfo

class ExpressInfoSerializer(serializers.ModelSerializer):
    """
    放到订单中的快递信息序列化
    """
    class Meta:
        model = ExpressInfo
        fields = "__all__"

class OrdersSerializer(serializers.ModelSerializer):
    """
    用户发布订单
    """
    users = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    # 生成订单时这些不用post
    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    nonce_str = serializers.CharField(read_only=True)
    pay_type = serializers.CharField(read_only=True)

    def get_station(self, instance):
        station = StationSerializer(instance=instance.station, many=False)
        return station.data

    def generate_order_sn(self):
        # 生成订单号
        # 当前时间+userid+随机数
        from random import Random
        import time
        random_ins = Random()
        order_sn = "{time_str}{userid}{ranstr}".format(time_str=time.strftime("%Y%m%d%H%M%S"),
                                                       userid=self.context["request"].user.id,
                                                       ranstr=random_ins.randint(10, 99))
        return order_sn

    def validate(self, attrs):
        # validate中添加order_sn，然后在view中就可以save
        attrs["order_sn"] = self.generate_order_sn()
        return attrs

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Orders
        fields = "__all__"

class UsersOrdersFindSerializer(serializers.ModelSerializer):
    """
    用户订单查询
    """
    users = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    station = serializers.SerializerMethodField()
    rider = serializers.SerializerMethodField()
    expressInfo = ExpressInfoSerializer(many=True)

    def get_station(self, instance):
        station = StationSerializer(instance=instance.station, many=False)
        return station.data

    def get_rider(self, instance):
        rider = RiderSerializer(instance=instance.rider)
        return rider.data

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Orders
        fields = '__all__'

class RobOrdersSerializer(serializers.ModelSerializer):
    """
    骑手抢单列表序列化器
    """
    station = serializers.SerializerMethodField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    nonce_str = serializers.CharField(read_only=True)
    pay_type = serializers.CharField(read_only=True)

    def get_station(self, instance):
        station = StationSerializer(instance=instance.station, many=False)
        return station.data

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Orders
        fields = "__all__"

class RiderRobOrdersSerializer(serializers.ModelSerializer):
    """
    骑手抢单序列化器
    """
    users = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )
    station = serializers.SerializerMethodField()
    rider = serializers.SerializerMethodField()
    post_script = serializers.CharField(read_only=True)
    order_mount = serializers.FloatField(read_only=True)
    pickup_code = serializers.CharField(read_only=True)
    address = serializers.CharField(read_only=True)
    signer_name = serializers.CharField(read_only=True)
    singer_mobile = serializers.CharField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    nonce_str = serializers.CharField(read_only=True)
    pay_type = serializers.CharField(read_only=True)

    def get_station(self, instance):
        station = StationSerializer(instance=instance.station, many=False)
        return station.data

    def get_rider(self, instance):
        rider = RiderSerializer(instance=instance.rider)
        return rider.data

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Orders
        fields = "__all__"

class RobOrdersDetailsSerializer(serializers.ModelSerializer):
    """
    骑手抢单详情序列化器
    """
    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    nonce_str = serializers.CharField(read_only=True)
    pay_type = serializers.CharField(read_only=True)
    station = serializers.SerializerMethodField()

    def get_station(self, instance):
        station = StationSerializer(instance=instance.station, many=False)
        return station.data

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Orders
        fields = "__all__"

class RiderOrdersSerializer(serializers.ModelSerializer):
    """
    骑手订单管理
    """
    users = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    station = serializers.SerializerMethodField()
    rider = serializers.SerializerMethodField()
    # expressInfo = ExpressInfoSerializer(many=True, read_only=True)
    # pay_status = serializers.CharField(read_only=True)
    # trade_no = serializers.CharField(read_only=True)
    # order_sn = serializers.CharField(read_only=True)
    # pay_time = serializers.DateTimeField(read_only=True)
    # nonce_str = serializers.CharField(read_only=True)
    # pay_type = serializers.CharField(read_only=True)
    post_script = serializers.CharField(read_only=True)
    order_mount = serializers.FloatField(read_only=True)
    pickup_code = serializers.CharField(read_only=True)
    address = serializers.CharField(read_only=True)
    signer_name = serializers.CharField(read_only=True)
    singer_mobile = serializers.CharField(read_only=True)
    pay_status = serializers.CharField(read_only=True)
    trade_no = serializers.CharField(read_only=True)
    order_sn = serializers.CharField(read_only=True)
    pay_time = serializers.DateTimeField(read_only=True)
    nonce_str = serializers.CharField(read_only=True)
    pay_type = serializers.CharField(read_only=True)

    def get_station(self, instance):
        station = StationSerializer(instance=instance.station, many=False)
        return station.data

    def get_rider(self, instance):
        rider = RiderSerializer(instance=instance.rider)
        return rider.data

    def is_valid(self, raise_exception=False):
        try:
            super().is_valid(raise_exception=True)
        except Exception as e:
            assert isinstance(e, ValidationError)
            for k, v in e.detail.items():
                raise ValidationError({"err_msg": v[0]})

    class Meta:
        model = Orders
        fields = "__all__"

class FindExpressInfoSerializer(serializers.ModelSerializer):
    """
    快递单号单独查询序列化器
    """

    orders = serializers.SerializerMethodField(read_only=True)

    def get_orders(self, instance):
        orders = UsersOrdersFindSerializer(instance=instance.orders, many=False)
        return orders.data

    class Meta:
        model = ExpressInfo
        fields = "__all__"